{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4d0fb839-ce51-4c19-9e9d-df00f9a89148",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from IPython.display import display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5ee67694-bd7b-4d6c-b3be-7b3a0990ff3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# List of file names\n",
    "file_names = ['sph01_112_ref_optim.txt', 'sph01_177_ref_optim.txt', 'sph01_251_ref_optim.txt',\n",
    "              'sph01_321_ref_optim.txt', 'sph02_27_ref_optim.txt', 'sph02_92_ref_optim.txt']\n",
    "\n",
    "# Corresponding condition names provided by the user\n",
    "conditions = [\n",
    "    'SPM w/o FeCl3 pH 3',\n",
    "    'SPM FeCl3 pH 2',\n",
    "    'SPM FeCl3 pH 3',\n",
    "    'SPM FeCl3 pH 4',\n",
    "    'SPM FeCl3 pH 5',\n",
    "    'SPM FeCl3 pH 7'\n",
    "]\n",
    "\n",
    "# Initialize an empty list to store the data\n",
    "data = []\n",
    "\n",
    "# Loop over each file\n",
    "for file_name, condition in zip(file_names, conditions):\n",
    "    with open(file_name, 'r') as file:\n",
    "        # Read the lines of the file\n",
    "        lines = file.readlines()\n",
    "        \n",
    "        # Create an empty list to store all the values from the file\n",
    "        values = []\n",
    "        \n",
    "        # Process each line and split if there are multiple values on a line\n",
    "        for line in lines:\n",
    "            # Split by whitespace and convert each part to a float\n",
    "            values.extend([float(val) for val in line.split()])\n",
    "\n",
    "        # Ignore the first 5 and last value, and ensure we have exactly 10 values\n",
    "        filtered_values = values[5:-1][:10]\n",
    "        \n",
    "        # Reorder the values: sigma1, d1, rho1, sigma2, d2, rho2, sigma3, d3, rho3, sigma4\n",
    "        reordered_values = [\n",
    "            filtered_values[2],  # sigma1\n",
    "            filtered_values[0],  # d1\n",
    "            filtered_values[1],  # rho1\n",
    "            filtered_values[5],  # sigma2\n",
    "            filtered_values[3],  # d2\n",
    "            filtered_values[4],  # rho2\n",
    "            filtered_values[8],  # sigma3\n",
    "            filtered_values[6],  # d3\n",
    "            filtered_values[7],  # rho3\n",
    "            filtered_values[9],  # sigma4\n",
    "        ]\n",
    "\n",
    "        # Append the condition and the reordered values\n",
    "        row = [condition] + reordered_values\n",
    "        data.append(row)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2b34ba0f-1f56-4be9-9e36-d16cbcece156",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated Table:\n",
      "            Condition sigma1    d1   rho1 sigma2    d2   rho2 sigma3    d3  \\\n",
      "0  SPM w/o FeCl3 pH 3    7.4   3.0  0.334    1.7  15.2  0.399    2.3  15.5   \n",
      "1      SPM FeCl3 pH 2    5.6  11.3  0.390    5.3  12.1  0.559    6.7  18.7   \n",
      "2      SPM FeCl3 pH 3    3.0  17.9  0.336    1.0  10.7  0.411    2.5  18.0   \n",
      "3      SPM FeCl3 pH 4   16.6   3.0  0.430    5.2  20.0  0.540    3.2  19.4   \n",
      "4      SPM FeCl3 pH 5    3.0  10.7  0.357    2.6  13.9  0.464    3.5  16.5   \n",
      "5      SPM FeCl3 pH 7   16.5  14.0  0.339    4.6   6.1  0.506    3.9  19.9   \n",
      "\n",
      "    rho3 sigma4  \n",
      "0  0.321    4.1  \n",
      "1  0.317    3.5  \n",
      "2  0.338    4.7  \n",
      "3  0.345    5.0  \n",
      "4  0.331    4.2  \n",
      "5  0.327    4.6  \n",
      "LaTeX Table:\n",
      "\\begin{tabular}{lllllllllll}\n",
      "\\toprule\n",
      "         Condition & sigma1 &   d1 &  rho1 & sigma2 &   d2 &  rho2 & sigma3 &   d3 &  rho3 & sigma4 \\\\\n",
      "\\midrule\n",
      "SPM w/o FeCl3 pH 3 &    7.4 &  3.0 & 0.334 &    1.7 & 15.2 & 0.399 &    2.3 & 15.5 & 0.321 &    4.1 \\\\\n",
      "    SPM FeCl3 pH 2 &    5.6 & 11.3 & 0.390 &    5.3 & 12.1 & 0.559 &    6.7 & 18.7 & 0.317 &    3.5 \\\\\n",
      "    SPM FeCl3 pH 3 &    3.0 & 17.9 & 0.336 &    1.0 & 10.7 & 0.411 &    2.5 & 18.0 & 0.338 &    4.7 \\\\\n",
      "    SPM FeCl3 pH 4 &   16.6 &  3.0 & 0.430 &    5.2 & 20.0 & 0.540 &    3.2 & 19.4 & 0.345 &    5.0 \\\\\n",
      "    SPM FeCl3 pH 5 &    3.0 & 10.7 & 0.357 &    2.6 & 13.9 & 0.464 &    3.5 & 16.5 & 0.331 &    4.2 \\\\\n",
      "    SPM FeCl3 pH 7 &   16.5 & 14.0 & 0.339 &    4.6 &  6.1 & 0.506 &    3.9 & 19.9 & 0.327 &    4.6 \\\\\n",
      "\\bottomrule\n",
      "\\end{tabular}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Define the column names in the desired order\n",
    "columns = ['Condition', 'sigma1', 'd1', 'rho1', 'sigma2', 'd2', 'rho2', 'sigma3', 'd3', 'rho3', 'sigma4']\n",
    "\n",
    "# Create the dataframe\n",
    "df = pd.DataFrame(data, columns=columns)\n",
    "\n",
    "# Format the values: 1 decimal for sigma and d columns, 3 decimals for rho columns\n",
    "df['rho1'] = df['rho1'].map(lambda x: f\"{x:.3f}\")\n",
    "df['rho2'] = df['rho2'].map(lambda x: f\"{x:.3f}\")\n",
    "df['rho3'] = df['rho3'].map(lambda x: f\"{x:.3f}\")\n",
    "df['d1'] = df['d1'].map(lambda x: f\"{x:.1f}\")\n",
    "df['d2'] = df['d2'].map(lambda x: f\"{x:.1f}\")\n",
    "df['d3'] = df['d3'].map(lambda x: f\"{x:.1f}\")\n",
    "df['sigma1'] = df['sigma1'].map(lambda x: f\"{x:.1f}\")\n",
    "df['sigma2'] = df['sigma2'].map(lambda x: f\"{x:.1f}\")\n",
    "df['sigma3'] = df['sigma3'].map(lambda x: f\"{x:.1f}\")\n",
    "df['sigma4'] = df['sigma4'].map(lambda x: f\"{x:.1f}\")\n",
    "# Display the dataframe\n",
    "print(\"Generated Table:\")\n",
    "print(df)\n",
    "\n",
    "# Generate LaTeX code for the table\n",
    "latex_table = df.to_latex(index=False, float_format=\"%.4f\")\n",
    "\n",
    "# Print the LaTeX table\n",
    "print(\"LaTeX Table:\")\n",
    "print(latex_table)\n",
    "\n",
    "# Save the table to a CSV file\n",
    "df.to_csv('generated_table.csv', index=False)\n",
    "\n",
    "# Save the LaTeX table to a text file\n",
    "with open('table_latex.txt', 'w') as f:\n",
    "    f.write(latex_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "af97595c-c6b0-40a2-beb9-f6a33f493254",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Creating the DataFrame from the given data\n",
    "data = {\n",
    "    'pH': ['SPM', 2, 3, 4, 5, 7],\n",
    "    'ED': [0.90827, 2.173, 3.4442, 4.1837, 0.96598, 0.81462],\n",
    "    'EDErr': [0.15366, 0.10468, 0.24121, 0.12543, 0.0037783, 0.040203]\n",
    "}\n",
    "\n",
    "df = pd.DataFrame(data)\n",
    "\n",
    "# Adding nfeXRF values to the DataFrame\n",
    "nfeXRF_values = [None, 0.976, 1.6, 3.392, 0.688, 0.024]\n",
    "nfeXRF_errors = [None, round(0.976 * 0.15, 4), round(1.6 * 0.15, 4), round(3.392 * 0.15, 4), round(0.688 * 0.15, 4), round(0.024 * 0.15, 4)]\n",
    "\n",
    "df['nfeXRF'] = nfeXRF_values\n",
    "df['nfeXRF_Err'] = nfeXRF_errors\n",
    "\n",
    "# Calculate deltagamma as the difference of ED between all pH and SPM\n",
    "df['deltagamma'] = df['ED'] - df.loc[0, 'ED']\n",
    "\n",
    "# Propagate the error for deltagamma\n",
    "df['deltagamma_Err'] = np.sqrt(df['EDErr']**2 + df.loc[0, 'EDErr']**2)\n",
    "\n",
    "# Update: Multiply deltagamma with 43 ± 2 to get deltaA and propagate the error\n",
    "multiplier = 43\n",
    "multiplier_err = 2\n",
    "\n",
    "df['deltaA'] = df['deltagamma'] * multiplier\n",
    "df['deltaA_Err'] = np.sqrt((df['deltagamma_Err'] * multiplier)**2 + (df['deltagamma'] * multiplier_err)**2)\n",
    "\n",
    "# Function to calculate NFe for each row based on the updated formula\n",
    "def calculate_NFe(deltaA, nfe, rhoW, V):\n",
    "    denominator = nfe - rhoW * V\n",
    "    return deltaA / denominator\n",
    "\n",
    "# Function to propagate errors for NFe calculations based on the updated formula\n",
    "def propagate_NFe_error(deltaA, deltaA_err, nfe, rhoW, V):\n",
    "    denominator = nfe - rhoW * V\n",
    "    deltaA_term_err = deltaA_err / denominator\n",
    "    return deltaA_term_err  # Error propagation only considers deltaA_err"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6ce139cc-9c48-4b97-bbd6-644772dd5a0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Using the previous values for nfe, rhoW, and V\n",
    "nfe = 85\n",
    "rhoW = 0.334\n",
    "V = 30\n",
    "\n",
    "# Calculating NFe for the first set of parameters\n",
    "nfe_values = []\n",
    "nfe_errors = []\n",
    "\n",
    "for i in range(1, len(df)):  # Skipping 'SPM'\n",
    "    nfe_value = calculate_NFe(df.loc[i, 'deltaA'], nfe, rhoW, V)\n",
    "    nfe_error = propagate_NFe_error(df.loc[i, 'deltaA'], df.loc[i, 'deltaA_Err'], nfe, rhoW, V)\n",
    "    nfe_values.append(nfe_value)\n",
    "    nfe_errors.append(nfe_error)\n",
    "\n",
    "df['NFe_85'] = [None] + nfe_values\n",
    "df['NFe_85_Err'] = [None] + nfe_errors\n",
    "\n",
    "# Calculating NFe for the second set of parameters (nfe = 53, rhoW = 0.334, V = 53.882)\n",
    "nfe = 53\n",
    "V = 53.882\n",
    "\n",
    "nfe_values_53 = []\n",
    "nfe_errors_53 = []\n",
    "\n",
    "for i in range(1, len(df)):  # Skipping 'SPM'\n",
    "    nfe_value_53 = calculate_NFe(df.loc[i, 'deltaA'], nfe, rhoW, V)\n",
    "    nfe_error_53 = propagate_NFe_error(df.loc[i, 'deltaA'], df.loc[i, 'deltaA_Err'], nfe, rhoW, V)\n",
    "    nfe_values_53.append(nfe_value_53)\n",
    "    nfe_errors_53.append(nfe_error_53)\n",
    "\n",
    "df['NFe_53'] = [None] + nfe_values_53\n",
    "df['NFe_53_Err'] = [None] + nfe_errors_53"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "97fb0142-ef8e-441f-a8ff-f0d81fd9f4d7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>pH</th>\n",
       "      <th>ED_with_Err</th>\n",
       "      <th>nfeXRF_with_Err</th>\n",
       "      <th>NFe_Fe(H2O)6_with_Err</th>\n",
       "      <th>NFe_Fe(OH)3_with_Err</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>SPM</td>\n",
       "      <td>0.9083 ± 0.1537</td>\n",
       "      <td>nan ± nan</td>\n",
       "      <td>nan ± nan</td>\n",
       "      <td>nan ± nan</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>2.173 ± 0.1047</td>\n",
       "      <td>0.976 ± 0.1464</td>\n",
       "      <td>0.7253 ± 0.1118</td>\n",
       "      <td>1.5537 ± 0.2396</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>3.4442 ± 0.2412</td>\n",
       "      <td>1.6 ± 0.24</td>\n",
       "      <td>1.4543 ± 0.1774</td>\n",
       "      <td>3.1153 ± 0.38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>4.1837 ± 0.1254</td>\n",
       "      <td>3.392 ± 0.5088</td>\n",
       "      <td>1.8784 ± 0.1434</td>\n",
       "      <td>4.0237 ± 0.3072</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>0.966 ± 0.0038</td>\n",
       "      <td>0.688 ± 0.1032</td>\n",
       "      <td>0.0331 ± 0.0882</td>\n",
       "      <td>0.0709 ± 0.1888</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>7</td>\n",
       "      <td>0.8146 ± 0.0402</td>\n",
       "      <td>0.024 ± 0.0036</td>\n",
       "      <td>-0.0537 ± 0.0911</td>\n",
       "      <td>-0.115 ± 0.1952</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    pH      ED_with_Err nfeXRF_with_Err NFe_Fe(H2O)6_with_Err  \\\n",
       "0  SPM  0.9083 ± 0.1537       nan ± nan             nan ± nan   \n",
       "1    2   2.173 ± 0.1047  0.976 ± 0.1464       0.7253 ± 0.1118   \n",
       "2    3  3.4442 ± 0.2412      1.6 ± 0.24       1.4543 ± 0.1774   \n",
       "3    4  4.1837 ± 0.1254  3.392 ± 0.5088       1.8784 ± 0.1434   \n",
       "4    5   0.966 ± 0.0038  0.688 ± 0.1032       0.0331 ± 0.0882   \n",
       "5    7  0.8146 ± 0.0402  0.024 ± 0.0036      -0.0537 ± 0.0911   \n",
       "\n",
       "  NFe_Fe(OH)3_with_Err  \n",
       "0            nan ± nan  \n",
       "1      1.5537 ± 0.2396  \n",
       "2        3.1153 ± 0.38  \n",
       "3      4.0237 ± 0.3072  \n",
       "4      0.0709 ± 0.1888  \n",
       "5      -0.115 ± 0.1952  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\\begin{tabular}{|c|c|c|c|c|}\n",
      "\\toprule\n",
      " pH &     ED\\_with\\_Err & nfeXRF\\_with\\_Err & NFe\\_Fe(H2O)6\\_with\\_Err & NFe\\_Fe(OH)3\\_with\\_Err \\\\\n",
      "\\midrule\n",
      "SPM & 0.9083 ± 0.1537 &       nan ± nan &             nan ± nan &            nan ± nan \\\\\n",
      "  2 &  2.173 ± 0.1047 &  0.976 ± 0.1464 &       0.7253 ± 0.1118 &      1.5537 ± 0.2396 \\\\\n",
      "  3 & 3.4442 ± 0.2412 &      1.6 ± 0.24 &       1.4543 ± 0.1774 &        3.1153 ± 0.38 \\\\\n",
      "  4 & 4.1837 ± 0.1254 &  3.392 ± 0.5088 &       1.8784 ± 0.1434 &      4.0237 ± 0.3072 \\\\\n",
      "  5 &  0.966 ± 0.0038 &  0.688 ± 0.1032 &       0.0331 ± 0.0882 &      0.0709 ± 0.1888 \\\\\n",
      "  7 & 0.8146 ± 0.0402 &  0.024 ± 0.0036 &      -0.0537 ± 0.0911 &      -0.115 ± 0.1952 \\\\\n",
      "\\bottomrule\n",
      "\\end{tabular}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Round all values to 4 decimal places\n",
    "df = df.round(4)\n",
    "\n",
    "# Combine values with errors in a single string\n",
    "df['ED_with_Err'] = df['ED'].astype(str) + ' ± ' + df['EDErr'].astype(str)\n",
    "df['nfeXRF_with_Err'] = df['nfeXRF'].astype(str) + ' ± ' + df['nfeXRF_Err'].astype(str)\n",
    "df['NFe_Fe(H2O)6_with_Err'] = df['NFe_85'].astype(str) + ' ± ' + df['NFe_85_Err'].astype(str)\n",
    "df['NFe_Fe(OH)3_with_Err'] = df['NFe_53'].astype(str) + ' ± ' + df['NFe_53_Err'].astype(str)\n",
    "\n",
    "# Final DataFrame with nfeXRF right after ED values\n",
    "final_table = df[['pH', 'ED_with_Err', 'nfeXRF_with_Err', 'NFe_Fe(H2O)6_with_Err', 'NFe_Fe(OH)3_with_Err']]\n",
    "\n",
    "# Display the DataFrame\n",
    "display(final_table)\n",
    "\n",
    "# Generate LaTeX code for the final table\n",
    "latex_code = final_table.to_latex(index=False, column_format=\"|c|c|c|c|c|\", bold_rows=True)\n",
    "print(latex_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96686751-c02d-42d9-ba0e-3b4f6128c5ed",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "430e6fc0-8018-4d72-ad62-1c1ddd2b9fbd",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
